"""
权限管理API端点
"""
from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException  # pyright: ignore[reportMissingImports]
from app.models.user import User
from app.api.deps import get_db
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]
from app.api.deps import get_current_user
from app.core.permissions import require_permission
from app.core.response import success_response, error_response, ErrorTypes, ErrorMessages, ApiResponse

router = APIRouter()

# 简化的权限定义 - 只分为查看、编辑、管理三个级别
PERMISSION_DEFINITIONS = {
    "project": {
        "name": "项目管理",
        "permissions": {
            "project:view": {"name": "查看项目", "level": "view"},
            "project:edit": {"name": "编辑项目", "level": "edit"},
            "project:manage": {"name": "管理项目", "level": "manage"}
        }
    },
    "task": {
        "name": "任务管理",
        "permissions": {
            "task:view": {"name": "查看任务", "level": "view"},
            "task:edit": {"name": "编辑任务", "level": "edit"},
            "task:manage": {"name": "管理任务", "level": "manage"}
        }
    },
    "user": {
        "name": "用户管理",
        "permissions": {
            "user:view": {"name": "查看用户", "level": "view"},
            "user:edit": {"name": "编辑用户", "level": "edit"},
            "user:manage": {"name": "管理用户", "level": "manage"}
        }
    },
    "role": {
        "name": "角色管理",
        "permissions": {
            "role:view": {"name": "查看角色", "level": "view"},
            "role:edit": {"name": "编辑角色", "level": "edit"},
            "role:manage": {"name": "管理角色", "level": "manage"}
        }
    },
    "permission": {
        "name": "权限管理",
        "permissions": {
            "permission:view": {"name": "查看权限", "level": "view"},
            "permission:edit": {"name": "编辑权限", "level": "edit"},
            "permission:manage": {"name": "管理权限", "level": "manage"}
        }
    },
    "requirement": {
        "name": "需求管理",
        "permissions": {
            "requirement:view": {"name": "查看需求", "level": "view"},
            "requirement:edit": {"name": "编辑需求", "level": "edit"},
            "requirement:manage": {"name": "管理需求", "level": "manage"}
        }
    },
    "document": {
        "name": "知识库",
        "permissions": {
            "document:view": {"name": "查看文档", "level": "view"},
            "document:edit": {"name": "编辑文档", "level": "edit"},
            "document:manage": {"name": "管理文档", "level": "manage"}
        }
    },
    "version": {
        "name": "版本管理",
        "permissions": {
            "version:view": {"name": "查看版本", "level": "view"},
            "version:edit": {"name": "编辑版本", "level": "edit"},
            "version:manage": {"name": "管理版本", "level": "manage"}
        }
    },
    "defect": {
        "name": "缺陷管理",
        "permissions": {
            "defect:view": {"name": "查看缺陷", "level": "view"},
            "defect:edit": {"name": "编辑缺陷", "level": "edit"},
            "defect:manage": {"name": "管理缺陷", "level": "manage"}
        }
    },
    "system": {
        "name": "系统管理",
        "permissions": {
            "system:view": {"name": "查看系统", "level": "view"},
            "system:edit": {"name": "编辑系统", "level": "edit"},
            "system:manage": {"name": "管理系统", "level": "manage"}
        }
    },
    "state": {
        "name": "状态管理",
        "permissions": {
            "state:view": {"name": "查看状态", "level": "view"},
            "state:edit": {"name": "编辑状态", "level": "edit"},
            "state:manage": {"name": "管理状态", "level": "manage"}
        }
    }
}

PERMISSION_MODULES = list(PERMISSION_DEFINITIONS.keys())    
# 权限级别定义
PERMISSION_LEVELS = {
    "view": {"name": "查看", "description": "只能查看相关信息", "color": "#67C23A"},
    "edit": {"name": "编辑", "description": "可以编辑相关信息", "color": "#E6A23C"},
    "manage": {"name": "管理", "description": "完全管理权限，包括创建、删除等", "color": "#F56C6C"}
}


@router.get("/definitions", response_model=ApiResponse, summary="获取权限定义")
async def get_permission_definitions(
    current_user: dict = Depends(get_current_user)
):
    """获取权限定义"""
    try:
        require_permission(current_user, "permission:view")
        
        data = {
            "modules": PERMISSION_MODULES,
            "levels": PERMISSION_LEVELS
        }
        
        return success_response(
            data=data,
            message="获取权限定义成功"
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"获取权限定义失败: {str(e)}"
        )


@router.get("/", response_model=ApiResponse, summary="获取所有权限列表")
async def get_all_permissions(
    current_user: dict = Depends(get_current_user)
):
    """获取所有权限列表"""
    try:
        require_permission(current_user, "permission:view")
        
        all_permissions = []
        
        for module_code, module_info in PERMISSION_DEFINITIONS.items():
            for perm_code, perm_info in module_info["permissions"].items():
                all_permissions.append({
                    "code": perm_code,
                    "name": perm_info["name"],
                    "level": perm_info["level"],
                    "module": module_code,
                    "module_name": module_info["name"]
                })
        
        return success_response(
            data=all_permissions,
            message="获取权限列表成功"
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"获取权限列表失败: {str(e)}"
        )


@router.get("/modules", response_model=ApiResponse, summary="获取权限模块列表")
async def get_permission_modules(
    current_user: dict = Depends(get_current_user)
):
    """
    获取权限模块列表
    使用 PermissionService.get_permission_groups() 获取完整的权限模块和权限列表
    """
    try:
        from app.services.permission_service import PermissionService
        
        # 使用 PermissionService 获取完整的权限分组
        permission_groups = PermissionService.get_permission_groups()
        
        # 权限级别映射（根据权限代码推断级别）
        def get_permission_level(perm_code: str) -> str:
            """根据权限代码推断权限级别"""
            if ":create" in perm_code or ":delete" in perm_code or ":manage" in perm_code:
                return "3"  # 高级权限
            elif ":update" in perm_code or ":edit" in perm_code or ":assign" in perm_code:
                return "2"  # 标准权限
            elif ":read" in perm_code or ":view" in perm_code or ":execute" in perm_code:
                return "1"  # 基础权限
            elif perm_code == "*":
                return "4"  # 管理权限
            else:
                return "2"  # 默认为标准权限
        
        from app.enums.permission import get_module_name
        
        modules = []
        for module_code, permissions in permission_groups.items():
            # 获取模块名称（使用枚举中的函数）
            module_name = get_module_name(module_code)
            
            # 转换权限格式
            perm_list = []
            for perm in permissions:
                perm_list.append({
                    "code": perm["value"],
                    "name": perm["label"],
                    "level": get_permission_level(perm["value"])
                })
            
            # 只添加有权限的模块
            if perm_list:
                modules.append({
                    "code": module_code,
                    "name": module_name,
                    "permissions": perm_list
                })
        
        # 按模块代码排序，确保顺序一致
        modules.sort(key=lambda x: x["code"])
        
        return success_response(
            data=modules,
            message="获取权限模块成功"
        )
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"获取权限模块失败: {str(e)}", exc_info=True)
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"获取权限模块失败: {str(e)}"
        )


@router.get("/levels", response_model=ApiResponse, summary="获取权限级别定义")
async def get_permission_levels(
    current_user: dict = Depends(get_current_user)
):
    """获取权限级别定义"""
    try:
        require_permission(current_user, "permission:view")
        
        return success_response(
            data=PERMISSION_LEVELS,
            message="获取权限级别成功"
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"获取权限级别失败: {str(e)}"
        )


@router.get("/check/{permission}", response_model=ApiResponse, summary="检查用户是否拥有指定权限")
async def check_permission(
    permission: str,
    current_user: dict = Depends(get_current_user)
):
    """检查用户是否拥有指定权限"""
    from app.core.permissions import has_permission
    
    has_perm = has_permission(current_user, permission)
    
    return success_response(
        data={
            "permission": permission,
            "has_permission": has_perm,
            "user_id": current_user.get("id"),
            "user_roles": current_user.get("roles", [])
        },
        message="权限检查完成"
    )


@router.get("/user/{user_id}", response_model=ApiResponse, summary="获取指定用户的权限列表")
async def get_user_permissions(
    user_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """获取指定用户的权限列表"""
    require_permission(current_user, "permission:view")
    
    # 如果查询当前用户自己的权限
    if user_id == current_user.get("id"):
        return success_response(
            data={
                "user_id": user_id,
                "roles": current_user.get("roles", []),
                "permissions": current_user.get("permissions", [])
            },
            message="获取用户权限成功"
        )
    
    # 如果查询其他用户，需要管理权限
    require_permission(current_user, "user:manage")
    
    # 从数据库获取用户信息
    from bson import ObjectId  # pyright: ignore[reportMissingImports]
    if not ObjectId.is_valid(user_id):
        raise HTTPException(
            status_code=400,
            detail="Invalid user ID format"
        )
    
    user = await db.users.find_one({"_id": ObjectId(user_id)})
    if not user:
        raise HTTPException(
            status_code=404,
            detail="User not found"
        )
    
    return success_response(
        data={
            "user_id": user_id,
            "roles": user.get("roles", []),
            "permissions": user.get("permissions", [])
        },
        message="获取用户权限成功"
    )


@router.get("/validate", response_model=ApiResponse, summary="验证权限代码是否有效")
async def validate_permissions(
    permissions: str,  # 逗号分隔的权限列表
    current_user: dict = Depends(get_current_user)
):
    """验证权限代码是否有效"""
    require_permission(current_user, "permission:view")
    
    perm_list = [p.strip() for p in permissions.split(",") if p.strip()]
    valid_permissions = []
    invalid_permissions = []
    
    # 获取所有有效权限
    all_valid_perms = set()
    for module_info in PERMISSION_DEFINITIONS.values():
        all_valid_perms.update(module_info["permissions"].keys())
    all_valid_perms.add("*")  # 管理员通配符权限
    
    for perm in perm_list:
        if perm in all_valid_perms:
            valid_permissions.append(perm)
        else:
            invalid_permissions.append(perm)
    
    return success_response(
        data={
            "valid_permissions": valid_permissions,
            "invalid_permissions": invalid_permissions,
            "total_checked": len(perm_list)
        },
        message="权限代码验证完成"
    )